import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/common/charts_pie.dart';
import 'package:enterprise_v6_app/app/data/entities/application/standardiztion/standard_home_edu_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/standardiztion/standard_home_edu_stat_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/standardiztion/standard_home_evaluate_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/standardiztion/standard_home_regulation_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/standardiztion/standard_home_risk_analysis_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/standardiztion/standard_home_risk_assess_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/standardiztion/standard_home_scence_facility_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/standardiztion/standard_home_scence_health_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/standardiztion/standard_home_scence_safe_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/standardiztion/standard_home_scence_sign_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/standardiztion/standard_home_target_cert_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/standardiztion/standard_home_target_resp_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/standardiztion/standard_home_urgent_count_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/standardiztion/standard_home_urgent_type_count_entity.dart';

const _orange = Color(0xFFFC9900);
const _blue = Color(0xFF33A9FF);
const _yellow = Color(0xFFFFCE24);
const _red = Color(0xFFFD6B6B);
const _colors = [_orange, _blue, _yellow, _red, Colors.cyan, Colors.purple, Colors.green];

/// 标准化总览
class StandardizationHomeController extends GetxController {
  /// 自评 or 他评
  bool isSelfEvaluate = true;

  /// 初始风险
  final initRiskCounts = [
    ChartData('重大风险', 10, Colors.blue),
    ChartData('一般风险', 20, Colors.green),
    ChartData('较大风险', 30, Colors.red),
    ChartData('低风险', 40, Colors.yellow),
  ];
  int get initRiskCount {
    return initRiskCounts.fold(0, (previousValue, element) => previousValue + element.y.toInt());
  }

  /// 剩余风险
  final leftRiskCounts = [
    ChartData('重大风险', 10, Colors.blue),
    ChartData('一般风险', 20, Colors.green),
    ChartData('较大风险', 30, Colors.red),
    ChartData('低风险', 40, Colors.yellow),
  ];
  int get leftRiskCount {
    return leftRiskCounts.fold(0, (previousValue, element) => previousValue + element.y.toInt());
  }

  /// 应急预案
  final urgentPlanCounts = [
    ChartData('综合应急预案', 10, Colors.blue),
    ChartData('专项应急预案', 20, Colors.green),
    ChartData('现场处置方案', 30, Colors.red),
    ChartData('重大活动方案', 40, Colors.yellow),
  ];
  int get urgentPlanCount {
    return urgentPlanCounts.fold(0, (previousValue, element) => previousValue + element.y.toInt());
  }

  /// 评估
  StandardHomeEvaluateEntity? evaluate;
  Future<void> getEvaluate() async {
    final resp = await HttpUtil()
        .generateGetRequest<StandardHomeEvaluateEntity>(
          '${Interface.mainBaseUrl}/standard//overview/getEvaluate',
        )
        .execute();
    resp.onSuccess((result) {
      if (result.data != null) {
        evaluate = result.data;
        update();
      }
    });
  }

  /// 现场标识
  StandardHomeScenceSignEntity? scenceSign;
  Future<void> getScenceSign() async {
    final resp = await HttpUtil()
        .generateGetRequest<StandardHomeScenceSignEntity>(
          '${Interface.mainBaseUrl}/standard//overview/getWarningSingStatusVo',
        )
        .execute();
    resp.onSuccess((result) {
      if (result.data != null) {
        scenceSign = result.data;
        update();
      }
    });
  }

  /// 现场作业
  StandardHomeScenceSafeEntity? scenceWork;
  Future<void> getScenceWork() async {
    final resp = await HttpUtil()
        .generateGetRequest<StandardHomeScenceSafeEntity>(
          '${Interface.mainBaseUrl}/standard//overview/jobSafetyVoFan',
        )
        .execute();
    resp.onSuccess((result) {
      if (result.data != null) {
        scenceWork = result.data;
        update();
      }
    });
  }

  /// 现场健康
  StandardHomeScenceHealthEntity? scenceHealth;
  Future<void> getScenceHealth() async {
    final resp = await HttpUtil()
        .generateGetRequest<StandardHomeScenceHealthEntity>(
          '${Interface.mainBaseUrl}/standard//overview/occupationHealth',
        )
        .execute();
    resp.onSuccess((result) {
      if (result.data != null) {
        scenceHealth = result.data;
        update();
      }
    });
  }

  /// 现场设施
  StandardHomeScenceFacilityEntity? scenceFacility;
  Future<void> getScenceFacility() async {
    final resp = await HttpUtil()
        .generateGetRequest<StandardHomeScenceFacilityEntity>(
          '${Interface.mainBaseUrl}/standard//overview/sceneDevice',
        )
        .execute();
    resp.onSuccess((result) {
      if (result.data != null) {
        scenceFacility = result.data;
        update();
      }
    });
  }

  /// 安全生产责任落实
  StandardHomeTargetRespEntity? targetResp;
  Future<void> getTargetResp() async {
    final resp = await HttpUtil()
        .generateGetRequest<StandardHomeTargetRespEntity>(
          '${Interface.mainBaseUrl}/standard//overview/ImplementationOfSafetyProductionResponsibilities',
        )
        .execute();
    resp.onSuccess((result) {
      if (result.data != null) {
        targetResp = result.data;
        update();
      }
    });
  }

  /// 设备证书
  final certDeviceCounts = <ChartData>[];
  int get certDeviceCount {
    return certDeviceCounts.fold(0, (previousValue, element) => previousValue + element.y.toInt());
  }
  /// 人员证书
  final certPersonCounts = <ChartData>[];
  int get certPersonCount {
    return certPersonCounts.fold(0, (previousValue, element) => previousValue + element.y.toInt());
  }
  /// 证书
  StandardHomeTargetCertEntity? targetCert;
  Future<void> getTargetCert() async {
    final resp = await HttpUtil()
        .generateGetRequest<StandardHomeTargetCertEntity>(
          '${Interface.mainBaseUrl}/standard//overview/certificateHolderStatus',
        )
        .execute();
    resp.onSuccess((result) {
      if (result.data != null) {
        targetCert = result.data;
        certDeviceCounts.clear();
        certPersonCounts.clear();
        
        for (final item in result.data!.deviceMap ?? <StandardHomeTargetCertDeviceMap>[]) {
          final name = item.name ?? '';
          if (certDeviceCounts.any((element) => element.x == name)) {
            final index = certDeviceCounts.indexWhere((element) => element.x == name);
            // 可能是后端示例数据错了，有时候会出现重复的name，暂时先覆盖，不叠加
            certDeviceCounts[index] = certDeviceCounts[index].copyWith(y: item.value ?? 0);
          } else {
            certDeviceCounts.add(ChartData(name, item.value ?? 0, _colors[certDeviceCounts.length % _colors.length]));
          }
        }
        for (final item in result.data!.personnelMap ?? <StandardHomeTargetCertPersonnelMap>[]) {
          final name = item.name ?? '';
          if (certPersonCounts.any((element) => element.x == name)) {
            // 同上
            final index = certPersonCounts.indexWhere((element) => element.x == name);
            certPersonCounts[index] = certPersonCounts[index].copyWith(y: item.value ?? 0);
          } else {
            certPersonCounts.add(ChartData(name, item.value ?? 0, _colors[certPersonCounts.length % _colors.length]));
          }
        }
        update();
      }
    });
  }

  int get targetCertLargest {
    final a = targetCert?.deviceSum ?? 0;
    final b = targetCert?.enterpriseSum ?? 0;
    final c = targetCert?.personnelSum ?? 0;
    final max = [a, b, c].reduce((value, element) => value > element ? value : element);
    return (max * 1.2).toInt();
  }

  /// 法律法规
  StandardHomeRegulationEntity? regulation;
  Future<void> getRegulation() async {
    final resp = await HttpUtil()
        .generateGetRequest<StandardHomeRegulationEntity>(
          '${Interface.mainBaseUrl}/standard//overview/getLawStatus',
        )
        .execute();
    resp.onSuccess((result) {
      if (result.data != null) {
        regulation = result.data;
        update();
      }
    });
  }

  int get regulationLargest {
    final a = regulation?.law ?? 0;
    final b = regulation?.rulesAndRegulations ?? 0;
    final max = [a, b].reduce((value, element) => value > element ? value : element);
    return (max * 1.2).toInt();
  }

  /// 风险分析
  StandardHomeRiskAnalysisEntity? risk;
  Future<void> getRisk() async {
    final resp = await HttpUtil()
        .generateGetRequest<StandardHomeRiskAnalysisEntity>(
          '${Interface.mainBaseUrl}/standard//overview/riskStatistics',
        )
        .execute();
    resp.onSuccess((result) {
      if (result.data != null) {
        risk = result.data;
        initRiskCounts.clear();
        initRiskCounts.addAll([
          ChartData('低风险', result.data?.initialRiskFour ?? 0, _orange),
          ChartData('一般风险', result.data?.initialRiskOne ?? 0, _red),
          ChartData('较大风险', result.data?.initialRiskThree ?? 0, _blue),
          ChartData('重大风险', result.data?.initialRiskTwo ?? 0, _yellow),
        ]);
        leftRiskCounts.clear();
        leftRiskCounts.addAll([
          ChartData('低风险', result.data?.riskFour ?? 0, _orange),
          ChartData('一般风险', result.data?.riskOne ?? 0, _red),
          ChartData('较大风险', result.data?.riskThree ?? 0, _blue),
          ChartData('重大风险', result.data?.riskTwo ?? 0, _yellow),
        ]);
        update();
      }
    });
  }

  /// 风险评估
  StandardHomeRiskAssessEntity? riskAssess;
  Future<void> getRiskAssess() async {
    final resp = await HttpUtil()
        .generateGetRequest<StandardHomeRiskAssessEntity>(
          '${Interface.mainBaseUrl}/standard//overview/threeRate',
        )
        .execute();
    resp.onSuccess((result) {
      if (result.data != null) {
        riskAssess = result.data;
        update();
      }
    });
  }

  int get actualRiskAnalysis {
    return (riskAssess?.analysisRate ?? 0) * (riskAssess?.analysisCount ?? 0) ~/ 100;
  }

  int get actualInvestigation {
    return (riskAssess?.investigationRate ?? 0) * (riskAssess?.investigationCount ?? 0) ~/ 100;
  }

  int get actualRectification {
    return (riskAssess?.rectificationRate ?? 0) * (riskAssess?.rectificationCount ?? 0) ~/ 100;
  }

  /// 应急管理
  StandardHomeUrgentCountEntity? urgentCount;
  Future<void> getUrgentCount() async {
    final resp = await HttpUtil()
        .generateGetRequest<StandardHomeUrgentCountEntity>(
          '${Interface.mainBaseUrl}/standard//overview/getEmergencyManagement',
        )
        .execute();
    resp.onSuccess((result) {
      if (result.data != null) {
        urgentCount = result.data;
        update();
      }
    });
  }

  /// 应急预案
  StandardHomeUrgentTypeCountEntity? urgentTypeCount;
  Future<void> getUrgentTypeCount() async {
    final resp = await HttpUtil()
        .generateGetRequest<StandardHomeUrgentTypeCountEntity>(
          '${Interface.mainBaseUrl}/standard//overview/getEmergencyTypeVo',
        )
        .execute();
    resp.onSuccess((result) {
      if (result.data != null) {
        urgentTypeCount = result.data;
        urgentPlanCounts.clear();
        urgentPlanCounts.addAll([
          ChartData('综合应急预案', result.data?.comprehensiveNum ?? 0, _orange),
          ChartData('专项应急预案', result.data?.specialNum ?? 0, _red),
          ChartData('现场处置方案', result.data?.sceneLiveNum ?? 0, _blue),
          ChartData('重大活动方案', result.data?.majorNum ?? 0, _yellow),
        ]);
        update();
      }
    });
  }

  /// 教育培训
  StandardHomeEduEntity? edu;
  Future<void> getEdu() async {
    final resp = await HttpUtil()
        .generateGetRequest<StandardHomeEduEntity>(
          '${Interface.mainBaseUrl}/standard//overview/getCompanyEduStatistics',
        )
        .execute();
    resp.onSuccess((result) {
      if (result.data != null) {
        edu = result.data;
        update();
      }
    });
  }

  final eduCounts = <ChartData>[
    ChartData('主要负责人', 0, _orange),
    ChartData('安全管理人员', 0, _red),
    ChartData('特种作业人员', 0, _blue),
    ChartData('企业在册从业人员', 0, _yellow),
    ChartData('专职安全人员', 0, Colors.cyan),
    ChartData('注册安全工程师', 0, Colors.purple),
    ChartData('外来人员', 0, Colors.green),
  ];
  final eduFinishCounts = <ChartData>[
    ChartData('主要负责人', 0, _orange),
    ChartData('安全管理人员', 0, _red),
    ChartData('特种作业人员', 0, _blue),
    ChartData('企业在册从业人员', 0, _yellow),
    ChartData('专职安全人员', 0, Colors.cyan),
    ChartData('注册安全工程师', 0, Colors.purple),
    ChartData('外来人员', 0, Colors.green),
  ];
  Future<void> getEduStat() async {
    final resp = await HttpUtil()
        .generateGetRequest<List<StandardHomeEduStatEntity>>(
          '${Interface.mainBaseUrl}/standard//overview/getCompanyEduTree',
        )
        .execute();
    resp.onSuccess((result) {
      if (result.data != null) {

        /// 类型 0：主要负责人 1：安全管理人员 2：特种作业人员 3：企业在册从业人员 4：专职安全人员 5：注册安全工程师 6:外来人员
        for (final item in result.data!) {
          switch (item.type) {
            case 0:
              eduCounts[0] = eduCounts[0].copyWith(y: item.eduCount ?? 0);
              eduFinishCounts[0] = eduFinishCounts[0].copyWith(y: item.finishCount ?? 0);
              break;
            case 1:
              eduCounts[1] = eduCounts[1].copyWith(y: item.eduCount ?? 0);
              eduFinishCounts[1] = eduFinishCounts[1].copyWith(y: item.finishCount ?? 0);
              break;
            case 2:
              eduCounts[2] = eduCounts[2].copyWith(y: item.eduCount ?? 0);
              eduFinishCounts[2] = eduFinishCounts[2].copyWith(y: item.finishCount ?? 0);
              break;
            case 3:
              eduCounts[3] = eduCounts[3].copyWith(y: item.eduCount ?? 0);
              eduFinishCounts[3] = eduFinishCounts[3].copyWith(y: item.finishCount ?? 0);
              break;
            case 4:
              eduCounts[4] = eduCounts[4].copyWith(y: item.eduCount ?? 0);
              eduFinishCounts[4] = eduFinishCounts[4].copyWith(y: item.finishCount ?? 0);
              break;
            case 5:
              eduCounts[5] = eduCounts[5].copyWith(y: item.eduCount ?? 0);
              eduFinishCounts[5] = eduFinishCounts[5].copyWith(y: item.finishCount ?? 0);
              break;
            case 6:
              eduCounts[6] = eduCounts[6].copyWith(y: item.eduCount ?? 0);
              eduFinishCounts[6] = eduFinishCounts[6].copyWith(y: item.finishCount ?? 0);
              break;
            default:
              break;
          }
        }
        update();
      }
    });
  }

  @override
  void onInit() {
    super.onInit();
    getEvaluate();
    getScenceSign();
    getScenceWork();
    getScenceHealth();
    getScenceFacility();
    getTargetResp();
    getTargetCert();
    getRegulation();
    getRisk();
    getRiskAssess();
    getUrgentCount();
    getUrgentTypeCount();
    getEdu();
    getEduStat();
  }
}
